package cn.com.zcode.core.xml;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

public class XmlReader {
	private Logger logger = Logger.getLogger(XmlReader.class);

	public <T extends XmlBean> Map<String, T> read(Set<File> list,Class<T> zlass) {
		Map<String, T> map = new LinkedHashMap<String, T>();
		if (list != null) {
			for (File file : list) {
				try {
					T job = this.load(file,zlass);
					if (job != null) {
						map.put(job.getKey(), job);
					}
				} catch (XmlException e) {
					e.printStackTrace();
					logger.error("fail to load file" + file);
				}
			}
		}
		return map;
	}

	private <T extends XmlBean> T load(File file,Class<T> zlass) throws XmlException {
		T obj = null;
		try {
			JAXBContext context = JAXBContext.newInstance(zlass);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			obj = (T) unmarshaller.unmarshal(file);
		} catch (JAXBException e) {
			e.printStackTrace();
			logger.error(e);
		}

		return obj;
	}

}
